import Model from '#Libs/dabase/model.js';

import { Sequelize } from 'sequelize';

import bcrypt from 'bcrypt';

import { empty } from '#Utils/helper.js';

class User extends Model {
    static async validatePwd(pwd, hash) {
        return await bcrypt.compare(pwd, hash);
    }

    static async isDisable(users) {
        return empty(users.deletedAt) ? false : true;
    }
}

User.setAttributes({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
    },
    name: {
        type: Sequelize.STRING,
        allowNull: false,
        defaultValue: '',
    },
    username: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    email: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
    },
})

User.setOptions({
    tableName: 'users',
    modelName: 'User',
    paranoid: true,
    timestamps: true,
    hooks: {
        beforeCreate: async (user, options) => {
            if (user.password) {
                user.password = await bcrypt.hash(user.password, 10);
            }
        },
        beforeUpdate: async (user, options) => {
            if (user.password) {
                user.password = await bcrypt.hash(user.password, 10);
            }
        }
    }
})


export default User;